package handels

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"strong-king-mgmt/cache"
	"strong-king-mgmt/models"
	"strong-king-mgmt/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "信息不可为空",
		})
		return
	}
	var user models.User
	models.DB.Where("username = ?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	if pkg.Md5Str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录成功",
			"data": user,
		})
		return
	}
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加成功",
		})
		return
	}
}
func UserListRole(c *gin.Context) {
	uid := c.Query("uid")
	/*
		       SELECT
			  *
			FROM
			  roles
			  LEFT JOIN user_roles ON user_roles.uid = roles.id
			WHERE
			  user_roles.uid = 1
	*/
	var list []models.Role
	models.DB.
		Table("roles").
		Where(" user_roles.uid = ?", uid).
		Joins(" LEFT JOIN user_roles ON user_roles.uid = roles.id").
		Find(&list)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func RoleListNode(c *gin.Context) {
	rid := c.Query("rid")
	/*
		   SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.rid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var list []models.Node
	models.DB.Table("nodes").
		Where("role_nodes.rid = ?", rid).
		Joins("LEFT JOIN role_nodes ON role_nodes.rid = nodes.id").
		Find(&list)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
